<template>
  <div :class="[videoBoxClass, error ? 'video_error' : '']" @touchstart="showToolBar" @touchend="hideToolBar">
		<!-- 播放器实例容器 -->
		<!-- v-if="courseInfo ? courseInfo.haveBuy : true" -->
		<div id="video-wrap" :class="modeSecondClass"></div>
		
		<!-- 控制栏容器 -->
		<div class="control-wrap" v-if="!error" :class="isFullScreen ? '' : modeSecondClass" :style="{zIndex: videoInfo.mode === 0 ? 12 : 5, overflow: 'hidden'}"> <!-- zIndex 修复分享按钮遮挡倍速面板 -->
			<!-- 横屏侧边倍速tab -->
			<transition name="tab">
				<div class="speed-tab" v-if="showSpeedTab">
					<ul>
						<li v-for="(speed, index) in speedArr" @touchend.stop="changeSpeed(index)" :key="index"><span :class="{select: speedIndex === index}">{{speed}} X</span></li>
					</ul>
				</div>
			</transition>
			<!-- 横屏清晰度tab -->
			<transition name="tab">
				<div class="speed-tab" v-if="showRatioTab">
					<ul>
						<li v-for="(ratio, index) in ratioList" @touchend.stop="changeRatio(index)" :key="index"><span :class="{select: ratioIndex === index}">{{ratio}}</span></li>
					</ul>
				</div>
			</transition>
			<!-- 横屏进度条 -->
			<transition name="control-bar">
				<!-- mode = 0: 横屏 1: 竖屏全屏 2: 竖屏半屏 -->
				<div class="control-bar" v-if="videoSrc && $store.state.duration && $store.state.duration > 0" v-show="isShowToolBar && isToolBar">
					<transition name="icon-bar">
						<!-- 预告和回看 -->
						<div v-if="(videoInfo.roomStatus !== '1' && (videoInfo.mode === 0 || videoInfo.mode === 2)) || (videoInfo.roomStatus !== '1' && isFullScreen) || (videoInfo.roomStatus === '0' )">
							<i class="i-btn" :class="{playing: isPlaying}" @touchstart.stop="controlBackVideo"></i>
							<div class="progress" @touchstart.stop="moveBar" @touchmove.stop="moveBar" @touchend.stop="leaveBar">
								<div class="bar"></div>
								<div class="played" :style="{width: `${videoCurrTime / videoDuraTime * 100}%`}">
									<i class="point"></i>
								</div>
								<div class="mask"></div>
							</div>
							<div class="time">{{`${timeRule(videoCurrTime)} / ${timeRule(videoDuraTime)}`}}</div>
							<div class="right-btn">
								<!-- 倍速 -->
								<div class="speed" @click.stop="openSpeedTab"><span>{{speedIndex === 3 ? '倍速' : speedArr[speedIndex] + ' X'}}</span></div>
								<div class="full-screen" :class="{cancel: isFullScreen}" @click.stop="setFullScreen" v-if="videoInfo.roomStatus !== '0'"></div>
							</div>
						</div>
						<!-- 直播 -->
						<div v-if="(videoInfo.roomStatus === '1' && (videoInfo.mode === 0 || videoInfo.mode === 2)) || (videoInfo.roomStatus === '1' && isFullScreen)">
							<i class="i-btn" :class="{playing: isPlaying}" @click.stop="controlBackVideo" style="width: 0 !important;"></i>
							<div class="right-btn">
								<!-- 清晰度 -->
								<div class="speed" @click.stop="openRatioTab" v-if="!isFullScreen"><span>{{ratioList[ratioIndex]}}</span></div>
								<div class="full-screen" :class="{cancel: isFullScreen}" @click.stop="setFullScreen" v-if="videoInfo.roomStatus !== '0'"></div>
							</div>
						</div> 
					</transition>
				</div>
			</transition>
			<!-- 低延迟标识 -->
			<!-- <i class="udp-icon" v-if="videoInfo.roomStatus === '1' && isRTC" :class="mode === 1 ? 'ps' : ''">RTC</i> -->
		</div>
		<!-- 播放器异常UI -->
		<div class="error-wrap" v-if="error" :class="[isFullScreen ? '' : modeSecondClass, videoInfo.mode === 1 ? 'ps_bg' : 'ls_bg']">
			<div class="error-container">
				<span class="error-tip">
					{{errList1.includes(errorInfo && errorInfo.paramData.error_code) ? '没有检测到视频流，请稍后进入或刷新重试下吧' : errList2.includes(errorInfo && errorInfo.paramData.error_code) ? '网络好像罢工了，请检查网络设备后重试' : '未知错误'}}
				</span>
				<div class="error-btn" @click="refreshPage">刷新重试</div>
				<span class="error-code" :class="[videoInfo.mode === 1 ? '' : 'ls-pos']">code：{{errorInfo ? errorInfo.paramData.error_code : '0000'}}</span>
			</div>
		</div>
  </div>
  <!--视频组件-->
  <!-- <div :class="[videoBoxClass]">
     <video controlslist="nodownload" id="video" :controls="$store.state.videoControlsState" :class="[modeSecondClass]" ref="videoref" @click.stop.prevent="videoBtn"
      @canplay="palyDuration" @durationchange="durationchange"  :src="videoSrc" x5-video-player-fullscreen="true"
      x5-video-player-type='h5-page' webkit-playsinline playsinline="" width="100%" v-if="courseInfo ? courseInfo.haveBuy : true">
      <span>您的手机版本，网页版暂未能支持！</span>
    </video>
    <div :class="[playBtnClass]" @click.stop.prevent="videoBtn" v-if="playBtnShow"></div>
  </div> -->
</template>
<script>
	import { mapState, mapMutations }  from 'vuex';
	import wx from 'weixin-js-sdk'
  export default {
    props: {
      videoInfo: Object,
      courseInfo: Object || null,
      type: String, //横竖屏
      status: String, //是直播还是回看
      progressShow: Boolean,
      playBtnShow: Boolean,
      progressL: Number,
      playBtn: Function,
			isToolBar: { //工具栏是否展示
				type: Boolean,
				default: true,
			}
    },
    data() {
      return {
        videoBoxClass: '',
        modeSecondClass: '', //模式2样式
        error: false,
        wScreenRrrorImg: false,
        hScreenRrrorImg: false,
        playBtnClass: 'play-btn',
        videoPlayState:true,//开关
        isRTC: false, // 低延迟标识
				ratioList: ['原画', '高清', '流畅'], // 可选清晰度
				ratioIndex: 0, // 清晰度标识，默认 0 = 原画
				showSpeedTab: false, // 倍速面板
				showRatioTab: false, // 清晰度面板
				isShowToolBar: true, // 工具栏
				isAutoPlay: false, // 自动播放标识
				isPlaying: false, // 预告回看是否正在播放
				isLivePlaying: true, // 直播是否正在播放
				firstClick: true,
				speedArr: [2, 1.5, 1.25, 1, 0.5], // 倍速
				speedIndex: 3, // 当前倍速
				isFullScreen: false, // 全屏标识
				curHtmlFontSize: document.querySelector('html').style.fontSize, // 当前html标签fontSize
				error: false, // 播放器异常标识
				errorInfo: null, // 异常信息
				// 提示用户异常，请尝试重新进入直播间
				errList1: [4001, 4002, 4007, 4012, 4100, 4116, 4200, 4011, 4013, 4015, 4016, 4017, 4400, 4115, 4010, 4118],
				// 提示用户切换网络
				errList2: [4003, 4004, 4005, 4006, 4008, 4009, 4014, 4500],
				channel: window.channel
      }
    },
    computed: {
      ...mapState(['videoSrc', 'setVideoState', 'appVisible', 'liveRoomClassInfo']),
			videoCurrTime() { // 当前视频播放的时长
				return this.$store.state.currTime
			},
			videoDuraTime() { // 当前视频播放的总时长
				return this.$store.state.duration
			},
			liveIsStart() { // 直播开始标识
				return this.$store.state.liveIsStart
			},
    },
    watch: {
      			// 监控全屏
			isFullScreen(bool) {
				document.querySelector('video').style.objectFit = bool ? 'contain' : 'fill'
				document.querySelector('video').style.height = bool ? '100%' : 'auto'
			},
			// 页面显示隐藏
			appVisible(bool) {
				if (this.error) return false
				if (document.querySelector('.prism-big-play-btn')) {
					if (bool) {
						document.querySelector('.prism-big-play-btn').style.display = 'none'
						this.player.play()
						this.$emit("playStatus", 1)
					} else {
						document.querySelector('.prism-big-play-btn').style.display = 'block'
						this.player.pause()
						this.$emit("playStatus", 2)
					}
				}
			},
			showBarrage(showBarrage) {
				const danmu = this.player.getComponent('AliplayerDanmuComponent')
				if (danmu) {
					if (showBarrage) {
						danmu.CM.start()
					} else {
						danmu.CM.stop()
						danmu.CM.clear()
					}
				}
			},
			setVideoState:{
				immediate:true,
				handler(newValue){
					if(this.player){
						if (['init', 'error'].includes(this.player.getStatus())) return false
						if(newValue == 'stopVideo'){
							document.querySelector('.prism-big-play-btn').style.display = 'block'
							this.player.pause()
							this.$emit("playStatus", 2)
						}else {
							document.querySelector('.prism-big-play-btn').style.display = 'none'
							this.player.play()
							this.$emit("playStatus", 1)
						}			
					}else{
						if(newValue == 'stopVideo'){
							this.isAutoPlay = false;
						}else {
							//关闭自动播放
							// this.isAutoPlay = true;
						}	
					}
				}
			},
       // 监视播放地址
			"$store.state.videoSrc": {
				handler(videoSrc) {
					this.$nextTick(() => {
						const { preImagUrl, mode, roomStatus, video } = this.videoInfo
						// 加载图修改
						const img = new Image();
						img.src = preImagUrl;
						img.onload = () => {
							if (this.error) return false
							if (img.width > img.height) {
								const loadingImg = document.querySelector('#video-wrap')
								if (mode === 1) {
									if (loadingImg) loadingImg.style.background = `url(${preImagUrl}) center/contain no-repeat`;
								} else if (mode === 3) {
									if (loadingImg) {
										const videoObj = document.createElement('video')
										videoObj.preload = 'metadata';
										videoObj.src = video;
										let width, height;
										videoObj.onloadedmetadata = function () {
											URL.revokeObjectURL(video);
											width = videoObj.videoWidth;
											height = videoObj.videoHeight;
											videoObj.remove()
											loadingImg.style.background = height > width
												? `url(${preImagUrl}) center/contain no-repeat`
												: `url(${preImagUrl}) center/cover no-repeat`
										}
									};
								} else {
									if (loadingImg) loadingImg.style.background = `url(${preImagUrl}) center/cover no-repeat`;
								}
							} else {
								if (mode === 0) {
									const loadingImg = document.querySelector('.width-video')
									if (loadingImg) loadingImg.style.background = `url(${preImagUrl}) center/contain no-repeat`;
								} else if (mode === 3) {
									const loadingImg = document.querySelector('.height-video')
									if (loadingImg) loadingImg.style.background = `url(${preImagUrl}) center/cover no-repeat`;
								} else {
									const loadingImg = document.querySelector('.height-video')
									if (loadingImg) loadingImg.style.background = `url(${preImagUrl}) center/cover no-repeat`;
								}
							}
						}
						// 判断视频源(有视频源初始化播放器，无视频源则显示背景图)
						if (videoSrc) {
							// 获取视频宽高
							const videoObj = document.createElement('video')
							videoObj.preload = 'metadata';
							videoObj.src = video;
							let width, height;
							videoObj.onloadedmetadata = function () {
								URL.revokeObjectURL(video);
								width = videoObj.videoWidth;
								height = videoObj.videoHeight;
								videoObj.remove()
							}
							// 销毁上一个aliplayer实例
							this.player?.dispose()
							// 判断是否开启低延迟
							this.isRTC = videoSrc.includes('artc://')
							// 判断清晰度（1 = 高清 2 = 标清）
							this.ratioIndex = videoSrc.includes('lhd') ? 1 : videoSrc.includes('lsd') ? 2 : 0
							// 初始化aliplayer
							this.$nextTick(() => {
								this.player = new Aliplayer({
									id: "video-wrap",
									source: videoSrc, // 视频源
									width: "100%",
									height: mode === 2 
										? ''
										: mode === 3 && height > width // 纯净视频判断 横屏 竖屏
											? ''
											: '100%',
									autoplay: this.isAutoPlay,
									// autoplay: false,
									cover: preImagUrl, // 封面
									isLive: roomStatus === '1', // 是否直播，直播状态禁止拖动进度条
									rePlay: false, // 自动循环播放
									liveRetry: 0, // 重试次数
									playsinline: true, // 内置播放
									preload: true, // 预加载
									controlBarVisibility: "always", // 控制面板显示方式（隐藏，使用自定义）
									useH5Prism: true, // 指定使用H5播放器
									skipRtsSupportCheck: true, // RTS环境支持检查getComment
									skinLayout: [ // 布局配置
										{
											"name": "bigPlayButton",
											"align": "cc"
										},
										{
											"name": "H5Loading",
											"align": "cc"
										},
										{
											"name": "errorDisplay",
											"align": "tlabs",
											"x": 0,
											"y": 0
										},
										{
											"name": "infoDisplay"
										},
										{
											"name": "tooltip",
											"align": "blabs",
											"x": 0,
											"y": 56
										},
										{
											"name": "thumbnail"
										},
										{
											"name": "controlBar",
											"align": "blabs",
											"x": 0,
											"y": 0,
											"children": []
										}
									],
									components: [{
										name: 'AliplayerDanmuComponent',
										type: AliPlayerComponent.AliplayerDanmuComponent,
										args: []
									}]
								}, player => {
									this.playStart(player) // 开始播放打点
									document.querySelector('video').style.opacity = '0';
									if (this.videoInfo.mode === 1) {
										document.querySelector('video').style.height = '100%';
									}
									this.$nextTick(async () => {
										// 初始化完毕loading和播放按钮同时出现问题
											setTimeout(() => {
											if (document.querySelector('.prism-big-play-btn')?.style.display === 'block') {
												const loadingDom = document.querySelector('.loading-center.prism-loading')
												if (loadingDom) {
												loadingDom.classList.add("prism-hide");
												}
											}
											}, 500);
										})
									// 悬浮屏出现弹幕问题
									document.querySelector('.prism-controlbar').style.display = 'none';
									document.querySelector('.prism-controlbar').style.overflow = 'hidden'
									document.querySelector('.prism-tooltip').style.display = 'none';
									// 屏幕点击暂停功能（预告，回看）
									if ((this.videoInfo.roomStatus !== '1' && this.videoInfo.mode === 1)) {
										document.querySelector('.control-wrap').addEventListener('click', () => this.videoBtn())
									}
									// 视频时间刷新
									player.on('timeupdate', () => this.durationchange())
									// 自动播放
									if (this.isAutoPlay) this.isPlaying = true
									const smallPlayBtn = document.querySelector('.prism-play-btn')
									const bigPlayBtn = document.querySelector('.prism-big-play-btn')
									if (smallPlayBtn) {
										smallPlayBtn.click()
									} else {
										bigPlayBtn.click()
									}
									// 解决ios不自动播放的问题
									(() => {
										wx.ready(() => {
											if (player) {
												this.setVideoState == 'stopVideo' ? palyer.pause() : player.play()
											}
										});
									})();
									// 由暂停切换为播放
									player.on('play', () => {
										this.$store.dispatch("setVideoIsPlayStatus", true);
										console.log('视频播放');
										this.$emit("playStatus", 1)
										this.isPlaying = true
										this.error = false
										this.hideToolBar()
									})
									// 视频真正开始播放
									player.on('playing', () => {
										if(this.courseInfo){
											//priceType  0-免费，1-付费  haveBuy true 购买 false 未购买
											const { haveBuy  } = this.courseInfo;
											if(!haveBuy){
												fun.toastMessage("若需观看请前往中信建投期货金建投APP“精品课程”栏目订阅该课程");
												player.pause()
												return 
											}
										}
										document.querySelector('video').style.opacity = '1';
										document.querySelector('#video-wrap').style.background = 'transparent'
										mode === 3 
											? document.querySelector('.height-video').style.background = 'transparent'
											: document.querySelector(mode === 0 ? '.width-video' : '.height-video').style.background = 'transparent';
										document.querySelector('video').style.background = '#000';
										if (this.videoPlayState) {
											this.videoPlayState = false;
											this.$store.dispatch("setVideoIsPlayStatus", true);
										}
										this.playBtn && this.playBtn()
										this.playBegin && this.playBegin()
									})
									// 由播放切换为暂停
									player.on('pause', () => {
										console.log('视频暂停');
										this.$store.dispatch("setVideoIsPlayStatus", false);
										//console.log('pause', 'play status', this.player.getStatus())
										this.isPlaying = false
										if (this.player.getStatus() === 'loading' || this.player.getStatus() === 'ready') {
										const loadingDom = document.querySelector('.circle')
										if (loadingDom) {
											loadingDom.classList.add("prism-hide");
										}
										}
									})
									// 检测是否可以自动播放
									player.on('autoplay', (data) => {
										if (data.paramData) { // 可以自动播放
											console.log('可以自动播放')
											this.isPlaying = true
										} else { // 不可以自动播放
											console.log('不可以自动播放')
											this.isPlaying = false
											// fun.toastMessage('由于当前浏览器限制自动播放，请手动点击播放！')
										}
									})
									// 播放结束
									player.on('ended', () => {
										console.log('播放结束');
										this.isPlaying = false;
										this.videoPlayState = true;
										this.$store.dispatch("setVideoIsPlayStatus", false);
										this.$emit("playStatus", 2)
									})
									// 全屏事件
									player.on('requestFullScreen', () => {
										// 将弹幕容器和控制栏容器移入video容器
										console.log('全屏')
										this.isFullScreen = true
										const controlWrap = document.querySelector('.control-wrap');
										const videoWrap = document.querySelector('#video-wrap');
										videoWrap.appendChild(controlWrap);
										// 监控当前全屏状态（非全屏切换fontSize）
										this.timeInterval && clearInterval(this.timeInterval)
										this.timeInterval = setInterval(() => {
											if (!player.fullscreenService.isFullScreen) {
												clearInterval(this.timeInterval)
												this.isFullScreen = false
												document.querySelector('html').style.fontSize = this.curHtmlFontSize
											}
										}, 200);
									})
									// 取消全屏事件
									player.on('cancelFullScreen', this.exitFullScreen)
								})
								// 流中断异常事件
								this.player.on('liveStreamStop', () => {
									this.$store.dispatch("setVideoIsPlayStatus", false);
									console.log('liveStreamStop')
									this.player.trigger('error', {
										error_code: 4400,
										error_msg: 'xxx'
									})
								})
								// 视频加载失败
								this.player.on('error', errorInfo => {
									console.log('视频加载失败');
									this.$store.dispatch("setVideoIsPlayStatus", false);
									this.setVideoErrorState(true)
                                    this.setLiveIsStart(false);
									this.errorInfo = errorInfo
									const code = errorInfo.paramData.error_code
									// 切换m3u8
									const codeList = {
										4110: '不支持webRTC',
										4111: '不支持此浏览器',
										4112: '浏览器版本过低',
										4113: '不支持H264',
										4114: 'create offer失败',
										4120: '创建offer错误, 浏览器不支持RTC',
										4122: 'answer失败'
									}
									if (codeList[code]) {
										fun.toastMessage('切换m3u8')
										sessionStorage.setItem('notRTC', true)
										// 区分互动课堂
										if (this.videoInfo.partnerId) {
											this.$store.commit('videoSrc', this.liveRoomClassInfo.hlsUrl)
										} else {
											this.$bus.$emit('changeTidAndRtc', { isRTC: false })
										}
									} else {
										this.error = true
									}
								})
							})
						}
					})
				},
				immediate: true
			},
			// 监控toolBar
			isShowToolBar: {
				handler(bool) {
					if (!this.videoSrc) {
						this.$bus.$emit('changeCountDown', true)
						this.isShowToolBar = false
						return false
					}
					if (this.showSpeedTab) return false; // 调速版显示，隐藏倒计时
					this.$bus.$emit('changeCountDown', !bool);
					this.hideToolBar()
				},
				immediate: true
			},
      progressL(val) {
        this.playCurrentTime(val)
      },
      playBtnShow(val) {
        // if (val) {
        //   this.$refs.videoref.pause();
        // } else {
        //   this.$refs.videoref.play();
        // }
      },
    },
    created() {
      if (this.type == 'wScreen') { //横屏
        this.videoBoxClass = 'width-video'
      } else if (this.type == 'hScreen') { //竖屏
        this.videoBoxClass = 'height-video';
        if (this.videoInfo.mode == 2) { //竖屏横画面
          this.playBtnClass = 'play-btn-mode2'
          this.modeSecondClass = 'mode-second-class';
        }
      }
    },
    mounted() {
		window.addEventListener('resize', () => {
			const w = document.documentElement.clientWidth;
			const h = document.documentElement.clientHeight;
			console.log('页面大小发生了变化', `宽度：${w}`, `高度：${h}`);
		});
      this.setVideoErrorState(false)
      if (this.type == 'wScreen') { //横屏
         this.$store.dispatch('setVideoControlsState',true)
      } else if (this.type == 'hScreen') { //竖屏
        if (this.videoInfo.mode == 2) { //调出系统播放器控件
          this.$store.dispatch('setVideoControlsState',true)
        }else{
          this.$store.dispatch('setVideoControlsState',false)
        }
      }
      window['hidePlug'] = (res) => { //机构号    // 1  悬浮   0其他恢复       0 暂停 1播放    0 静音 1非静音
        switch (this.$channel){
          case 'zxjt':
			   // orgNum|机构号，固定值 zxjt
			   // isFloat|1 表示 悬浮   0表示恢复直播页面
			   // isPause|0表示 暂停 1表示继续播放
				let data;
				if(window.terminal.isZxjtIos){
					data = res;
					console.log("原始数据",data)
				}else if(window.terminal.isZxjtAndroid){
					console.log("安卓解析前的数据----------",res)
					data = JSON.parse(res);
					console.log("安卓解析后的数据----------",data)
				}
             this.fullScreenVideoDom(data.isFloat,data.isPause);
            break;
          default:
            break;
        }
      }
      if (this.courseInfo) {
        this.$watch('courseInfo.haveBuy', function (val) {
          if (val) this.bindEvent();
        })
      } else {
        this.bindEvent();
      }
      this.$bus.$on('changePlay', val => {
				if (!this.player) return false
				document.querySelector('.prism-big-play-btn').style.display = val === 1 ? 'none' : 'block'
				val === 1 ? this.player.play() : this.player.pause()
			})
			this.$bus.$on('changeRatio', index => {
				index = index * 1
				if (index === this.ratioIndex) return false
				fun.toastMessage('清晰度切换为' + this.ratioList[index])
				this.$store.commit('changeRatio', index)
				this.$bus.$emit('changeTidAndRtc', {
					tid: index === 0 ? '' : index === 1 ? 'saas-lhd' : 'saas-lsd'
				})
			})
			this.$bus.$on('setFullScreen', () => {
				this.setFullScreen()
			})
    },
    methods: {
      ...mapMutations(['setVideoErrorState','setLiveIsStart']),
      bindEvent() {
        // this.$refs.videoref.onplaying = () => {//ontimeupdate  onpalying 视频真正开始播放
        //   if(this.videoPlayState){
        //     this.videoPlayState = false;
        //     this.$store.dispatch("setVideoIsPlayStatus", true);
        //   }
  
        // }
        // this.$refs.videoref.onended = () => {
        //   this.videoPlayState = true;
        //   this.$store.dispatch("setVideoIsPlayStatus", false);
        // }
      },
      
			// 发送弹幕方法
			sendDanmu(val) {
				if (this.player) {
					this.player.getComponent('AliplayerDanmuComponent').send({
						"mode": 1,            // mode 表示弹幕的类型，参考 弹幕类型 https://github.com/jabbany/CommentCoreLibrary/blob/master/docs/CommentTypes.md
						"text": val,       		// text 表示弹幕的文字内容。注意：在创造弹幕对象后，对 text 的更改将无意义。
						"stime": 1000,        // stime 表示弹幕相对于视频位置的开始时间（ms），0即在视频开始立即出现
						"size": 20,           // 弹幕的文字大小
						"color": 0xffffff     // 文字颜色
					})
				}
			},
      // 全屏控制
			setFullScreen() {
				if (this.player) {
					this.isFullScreen = !this.isFullScreen
					const htmlEle = document.querySelector('html')
					if (this.isFullScreen) {
						this.player.fullscreenService.requestFullScreen();
						// 原生 全屏 dom.requestFullScreen(); 退出全屏dom.exitFullscreen()
						// 监控IOS退出全屏
						document.querySelector('video').addEventListener('webkitendfullscreen', () => {
							document.querySelector('.prism-big-play-btn').style.display = 'block';
							this.player.pause();
							this.$emit("playStatus", 2)
							this.exitFullScreen()
						})
						document.querySelector('video').onfullscreenerror = function (event) {
							console.log("FULL SCREEN DENIED 全屏接口出错");
					    };
						//离开画中画
						document.querySelector('video').addEventListener("leavepictureinpicture", (event) => {
							//alert('离开画中画')
						});
						//竖屏情况或IOS设备下不需要改变fontSize
						if (this.videoInfo.mode !== 1 && !(window.terminal.iPhone || window.terminal.iPad)) {
							const preFontSize = this.curHtmlFontSize
							let index = 0
							const checkFontsize = () => {
								setTimeout(() => {
									// 修改html fontSize
									htmlEle.style.fontSize = preFontSize
									// 判断是否已修改fontsize（循环20次 | 判断是否修改）
									if (index++ > 20) {
										console.log('fontsize check end')
									} else {
										checkFontsize()
									}
								}, 50)
							}
							checkFontsize()
						}
					} else {
						document.querySelector('html').style.fontSize = this.curHtmlFontSize
						this.player.fullscreenService.cancelFullScreen()
					}
				}
			},
			// 退出全屏
			exitFullScreen() {
				console.log('取消全屏')
				this.isFullScreen = false
				document.querySelector('html').style.fontSize = this.curHtmlFontSize
				// 控制栏容器移出video容器
				const controlWrap = document.querySelector('.control-wrap');
				const videoWrap = document.querySelector('#video-wrap');
				console.log('容器测试', controlWrap, videoWrap)
				controlWrap && videoWrap.parentElement.appendChild(controlWrap);
			},
			// 触摸打开工具栏
			showToolBar() {
				if (!this.videoSrc) return false
				if (this.isShowToolBar) {
					this.isShowToolBar = false;
				} else {
					this.isShowToolBar = true;
					this.showSpeedTab = false;
					this.showRatioTab = false;
				}
			},
			// 收起工具栏（3s）
			hideToolBar() {
				clearTimeout(this.timeId)
				this.timeId = setTimeout(() => {
					this.isShowToolBar = false
				}, 3000);
			},
			// 拖动进度条
			moveBar (e) {
				// 暂停视频
				this.player.pause();
				clearTimeout(this.timeId)
				if (e.touches.length === 0) return false
				let percent = (e.touches[0].clientX - e.target.getBoundingClientRect().left) / e.target.clientWidth
				if (percent < 0) percent = 0;
				if (percent > 1) percent = 1;
				this.player.seek(this.$store.state.duration * percent)
				this.durationchange()
			},
			// 松开进度条
			leaveBar(e) {
				this.moveBar(e)
				this.player.play()
				this.hideToolBar()
			},
			// 预告回看video控制
			controlBackVideo() {
				this.isPlaying = !this.isPlaying
				this.$bus.$emit('changePlay', this.isPlaying ? 1 : 2)
			},
			// 直播video控制
			controlLiveVideo() {
				const newVideo = document.querySelector('.live-video')
				this.isLivePlaying = !this.isLivePlaying
				this.isLivePlaying ? newVideo.play() : newVideo.pause()
			},
			// 打开调速板
			openSpeedTab() {
				clearTimeout(this.timeId)
				this.isShowToolBar = false
				this.showSpeedTab = true
			},
			// 倍速修改
			changeSpeed(index) {
				this.speedIndex = index
				const speed = this.speedArr[index]
				this.player.setSpeed(speed)
				this.showSpeedTab = false
				fun.toastMessage(`当前倍速为 ${speed}X`)
			},
			// 打开清晰度板
			openRatioTab() {
				clearTimeout(this.timeId)
				this.isShowToolBar = false
				this.showRatioTab = true
			},
			// 清晰度修改
			changeRatio(index) {
				if (index !== this.ratioIndex) {
					this.$store.commit('changeRatio', index)
					console.log('切换' + this.ratioList[index])
					fun.toastMessage('清晰度切换为' + this.ratioList[index])
					this.$bus.$emit('changeTidAndRtc', {
						tid: index === 0 ? '' : index === 1 ? 'saas-lhd' : 'saas-lsd'
					})
				} else {
					fun.toastMessage('当前清晰度为' + this.ratioList[index])
				}
				this.showRatioTab = false
			},
		fullScreenVideoDom(isFloat, isPause) { //播放器全屏播放   // 1  悬浮   其他恢复
			if (isFloat == '1') { //悬浮
				if (window.terminal.isZxjtApp) {
					this.$store.commit('setShowMarginTop', false)
				}
				switch (this.videoInfo.mode) {//0 横屏模式  1竖屏全模式  2竖屏横画面
					case 0:
					case 1:
						this.videoBoxClass = 'full-screen-video-box'
						break;
					case 2:
						this.modeSecondClass = 'float-second-mode-class'
						break;
					default:
						break;
				}
			} else { //还原
				if (window.terminal.isZxjtApp) {
					const { mode } = this.videoInfo;
					if(mode ==  0){
						this.$store.commit('setShowMarginTop', true)
					}					
					//浮窗还原神策打点
					if (this.status === 'living') {
						if (this.videoInfo.roomStatus !== undefined) {
							const { title, anchor, roomId, roomStatus } = this.videoInfo;
							$sensorsTrack('liveBroadcast_floatingWindowClick', {
								user_nickname: this.$store.state.userInfo.nickname,
								live_room_id: roomId,
								live_room_name: title,
								live_room_status: ['预告', '直播中'][roomStatus],
								live_room_creator: anchor,
								function_name: '返回直播间',
							});
						}
					}else{
							const { title, creator } = this.videoInfo;
							$sensorsTrack('liveBroadcast_floatingWindowClick', {
								user_nickname: this.$store.state.userInfo.nickname,
								live_room_id: this.$route.params.id,
								live_room_name: title,
								live_room_status: '回看',
								live_room_creator: creator,
								function_name: '返回直播间',
							});
					}
				}
				switch (this.videoInfo.mode) {
					case 0:
						this.videoBoxClass = 'width-video';
						this.$store.dispatch('setVideoControlsState', true)
						break;
					case 1:
						this.videoBoxClass = 'height-video';
						break;
					case 2:
						this.modeSecondClass = '';
						this.$store.dispatch('setVideoControlsState', true)
						this.modeSecondClass = 'mode-second-class';
						break;
					default:
						break
				}
				let video = document.getElementById("video");
				if (isPause == '0' && window.terminal.iPhone) {//静音
					video.pause();
				}
				if (window.terminal.isZxjtApp) {
					if (window.terminal.iPhone && video.paused && isPause == '1') {
						video.play();
					}
				}
			}
		},
      // 视频加载失败
      videoLoadError() {
        this.error = true;
        this.$emit("getVideoLoading", false);
      },
      //预告 回看 播放/暂停功能
      videoBtn() {
        if (this.videoInfo.mode > 0 && this.videoInfo.roomStatus !== '0') { //竖屏
          if (this.player.getStatus() === 'playing' || this.player.getStatus() === 'ready') {
						document.querySelector('.prism-big-play-btn').style.display = 'block'
						this.player.pause()
						this.$emit("playStatus", 2)
					} else {
						document.querySelector('.prism-big-play-btn').style.display = 'none'
						this.player.play()
						this.$emit("playStatus", 1)
					}
        }
        // if (this.videoInfo.mode > 0) { //竖屏
        //   if (this.videoInfo.mode == 2) return; //全屏横
        //   if (this.videoInfo.roomStatus == '0' || this.videoInfo.roomStatus == undefined) { //预告  回看
        //     let isPaused = this.$refs.videoref.paused //暂停
        //     if (isPaused) {
        //       this.$refs.videoref.play()
        //       this.$emit("playStatus", 1)
        //     } else {
        //       this.$refs.videoref.pause()
        //       this.$emit("playStatus", 2)
        //     }
        //   }
        // }
      },
		playStart(player) { //点击视频播放按钮开始播放
			if (!this.error) player.play();
			if (this.status === 'living') {
				if (this.videoInfo.roomStatus !== undefined) {
					// 神策打点（播放-直播）
					const { title, anchor, roomId, roomStatus } = this.videoInfo;
					$sensorsTrack('liveBroadcast_liveRoomDetailsPageFunctionClick', {
						page_name: `直播${['预告', '详情'][roomStatus]}页`,
						user_nickname: this.$store.state.userInfo.nickname,
						live_room_id: roomId,
						live_room_name: title,
						live_room_status: ['预告', '直播中'][roomStatus],
						live_room_creator: anchor,
						function_name: '点击播放',
					});
				}
			} else {
				// 神策打点（播放-回看）
				const { title, creator } = this.videoInfo;
				$sensorsTrack('liveBroadcast_liveRoomDetailsPageFunctionClick', {
					page_name: `回看详情页`,
					user_nickname: this.$store.state.userInfo.nickname,
					live_room_id: this.$route.params.id,
					live_room_name: title,
					live_room_status: '回看',
					live_room_creator: creator,
					function_name: '点击播放',
				});
			}
		},
      //获取当前播放的时长
      playCurrentTime(val) {
        if (val || val === 0) {
          this.$refs.videoref.currentTime = val * this.$refs.videoref.duration / 100;
        }
        // 查看视频是否结束
        if (this.$refs.videoref.ended) {
          this.$emit("playStatus", 2);
        }
        if (this.$refs.videoref.duration) {
          let progress = (this.$refs.videoref.currentTime) / this.$refs.videoref.duration * 100;
          this.$emit("getProgress", progress);
        }
        this.$store.dispatch("getCurrTime", this.$refs.videoref.currentTime);
      },
      durationchange() {
        this.$store.dispatch("getCurrTime", this.player.getCurrentTime());
				this.$store.dispatch("getDuration", this.player.getDuration())
      },
      //获取播放总时长
      palyDuration() {
        if ( this.$refs.videoref.duration > 0) {
          this.$emit("getVideoLoading", false);
          this.$store.dispatch("getDuration", this.$refs.videoref.duration);
        }
      },
      	// 时间格式化
			timeRule(t) {
        if (!t) return `00:00:00`;
				let h = Math.floor(t/3600); // 小时
				let m = Math.floor((t%3600)/60); // 分
				let s = Math.floor((t%3600)%60); // 秒
				let hour = /^\d$/.test(h) ? '0' + h : h;
				let min = /^\d$/.test(m) ? '0' + m : m;
				let sec = /^\d$/.test(s) ? '0' + s : s;
				return `${hour}:${min}:${sec}`
				/* if (hour == '00') {
					return time = `${min}:${sec}`
				} else {
					return time = `${hour}:${min}:${sec}`
				} */
			},
      			// 播放器异常刷新按钮
			refreshPage() {
				if (this.$channel == "msyh" && !window.isIos && window.terminal.isMsyhApp) {
					console.log('1')
					function updateUrl(url, key) {
						var key = (key || 't') + '='; // 默认是"t"
						var reg = new RegExp(key + '\\d+'); // 正则：t=1472286066028
						var timestamp = +new Date();
						if (url.indexOf(key) > -1) { //有时间戳，直接更新
							return url.replace(reg, key + timestamp);
						} else { // 没有时间戳，加上时间戳
							if (url.indexOf('\?') > -1) {
								var urlArr = url.split('\?');
								if (urlArr[1]) {
										return urlArr[0] + '?' + key + timestamp + '&' + urlArr[1];
								} else { return urlArr[0] + '?' + key + timestamp; }
							} else {
								if (url.indexOf('#') > -1) {
											return url.split('#')[0] + '?' + key + timestamp + location.hash;
								} else { return url + '?' + key + timestamp; }
							}
						}
					}
					window.location.href = updateUrl(window.location.href)
				} else {
					console.log('2')
					window.location.reload(true)
				}
			}
    },
    beforeDestroy(){
		// 退出回看保存进度
		if(this.status!='living' && this.$refs.videoref){
			let currentTime= this.$refs.videoref.currentTime
			let duration = this.$refs.videoref.duration
			let percentage = 0
			if(currentTime>0){
			   percentage = (currentTime/duration*100).toFixed(2)+'%'
			}
			this.$store.dispatch("getPercentage", percentage);
			}
      // 清除播放地址
			this.$store.commit('videoSrc', '')
			// 销毁播放器实例
			this.player && this.player.dispose()
			// 清除定时器
			clearTimeout(this.timeId)
			// 恢复fontsize
			document.querySelector('html').style.fontSize = this.curHtmlFontSize
	},
  destroyed() {
			this.$store.dispatch("setVideoIsPlayStatus", false);//视频播放状态 未播放
			// 清除自定义事件
			this.$bus.$off()
    },
  }
</script>

<style scoped="scoped" lang="less">
/deep/ .prism-player {
  background: transparent;
  > .abp {
    > .container {
      > .cmt {
        opacity :0.7;
      }
    }
  }
  > video {
    height :auto;
    object-fit: cover;
  }
  > .prism-big-play-btn {
    background: url(../assets/images/playicon.png) center/100% no-repeat;
    > .outter {
      border: none
    }
  }
  > .prism-ErrorMessage {
    display: none !important;
  }
  > .prism-info-display {
    display: none !important;
  }
  > .prism-tooltip {
    display: none !important;
  }
  > .prism-controlbar {
    display: none !important;
    overflow: hidden !important;
    > .prism-controlbar-bg {
      display: none !important;
    }
    > .ali-danmuku-control {
      display: none !important;
    }
  }
  > .prism-cover {
    display: none !important;
  }
}
.pre-view {
  width :100vw !important;
  height: 424px !important;
  position: absolute !important;
  left: 0;
  top :0;
  z-index :1007;
}
  .tip-w-screen {
    width: 100vw;
    height: 424px;
    background: url(../assets/images/loadVideo.png) no-repeat;
    background-size: cover;
  }

  .tip-h-screen {
    width: 100vw;
    height: 100vh;
    background: url(../assets/images/loadVideoS.png) no-repeat;
    background-size: cover;
  }

  .width-video {
    width: 100%;
    height: 424px;
    position :relative;
	overflow: hidden;
	z-index: 2;
  }
  .float-second-mode-class{
	  width:100%;
	  height: 424px;
	  position: absolute;
	  top: 0;
	  left: 0;
	  z-index: 1000000;
  }
  .width-video video,
  .width-video .tips {
    width: 100%;
    height: 424px;
    color: black;
  }

  .height-video,
  .height-video .tips {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    position: relative;
    align-items: center;
    color: #ffffff;
  }

  .tips img {
    width: 100%;
  }


  .mode-second-class {
    position: absolute;
    top: 320px !important;
    left: 0;
    width: 100%;
    height: 424px !important;
  }

  .tips {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .play-btn {
    width: 120px;
    height: 120px;
    background: url(../assets/images/play-img.svg) no-repeat;
    background-size: 120px 120px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -60px;
    margin-left: -60px;
    z-index: 1;
  }

  .play-btn-mode2 {
    width: 120px;
    height: 120px;
    background: url(../assets/images/play-img.svg) no-repeat;
    background-size: 120px 120px;
    position: absolute;
    top: 37%;
    left: 50%;
    margin-top: -60px;
    margin-left: -60px;
    z-index: 1;
  }

  .full-screen-video-box {
    width: 100vw !important;
    height: 100vh !important;
    position: fixed;
    top: 0 ;
    left: 0;
    z-index: 1000000000;
  }
/*  .full-screen-video-box video{
    width: 100vw !important;
    height: 100vh !important;
  } */
  .dianwo{
    position: absolute;
    top: 10.75rem;
    left: 20px;
    z-index: 1555;
  }
  .player-con{
		width : 100%;
		height : 100%;
		position : relative;
		overflow : hidden;
		display :flex;
		justify-content : center;
		align-items : center;
  }
	#video-wrap{
		width: 100%;
		height: 424px;}
		.live-video
			{object-fit: contain;}
	.tab-enter-active, .tab-leave-active {
		transition: transform .5s;
  }
	.tab-enter, .tab-leave-to {
		transform: translateX(100%);
  }
	// 独立播放/暂停按钮
	.i-btn{
		width: 60px;
		height: 60px;
		display :block;
		position: absolute;
		left: 34px;
		bottom: 14px;
		z-index: 10;
		background: url(../assets/images/playing.png) no-repeat;
		background-size :60px 60px;
		&.playing{
			background: url(../assets/images/pause.png) no-repeat;
			background-size: 60px 60px;
    }
    }
	.udp-icon{
		display: block;
		position: absolute;
		top: 20px;
		right :20px;
		z-index: 10;
		color: #fff;
		border :1px solid #fff;
		padding: 2px 5px;
		font-style :initial;
		font-size: 12px;
		&.ps{
      top: 180px;
    }
    }
	// 工具栏
	.control-bar-enter-active, .control-bar-leave-active{
		transition :all .5s;
  }
	.control-bar-enter, .control-bar-leave-to
		{transform: translateY(100%);
		opacity: 0;}
	.control-bar{
		width: 100%;
		height :87px;
		position :absolute;
		left: 0;
		bottom :0;

		.icon-bar-enter-active, .icon-bar-leave-active
			{transition: transform .5s;}
		.icon-bar-enter, .icon-bar-leave-to
			{transform: translateY(100%);}
		> div{
			width: 100%;
			height :100%;
			display :flex;
			justify-content :space-between;
			align-items:center;
			padding: 0px 30px;
			background: linear-gradient(180deg, rgba(0,0,0,0) 0%, rgba(0,0,0,.7));
			> .i-btn
				{position :initial;}
			}
			.progress{
				height: 100%;
				margin-left: 15px;
				flex :1;
				position: relative;
				> .bar{
					width :100%;
					height: 6px;
					background :rgba(255,255,255,.5);
					position: absolute;
					left: 0;
					top: 50%;
					transform: translateY(-50%);
					border-radius: 3px;}
				> .played{
					width :0%;
					height: 6px;
					background: #fff;
					position :absolute;
					left: 0;
					top: 50%;
					transform: translateY(-50%);
					border-radius: 3px;}
					> .point{
						width: 15px;
						height: 15px;
						background: #fff;
						position: absolute;
						right: -5px;
						top :50%;
						transform: translateY(-50%);
						border-radius: 50%;}
				> .mask{
					width: 100%;
					height :100%;
					position: absolute;
					top :0;
					left :0;}
				}
			.time{
				margin-left: 15px;
				color: #fff;
				font-size :24px;}
            
				.right-btn{
				display :flex;
				align-items: center;
				justify-content :space-between;
				height: 100%;
				line-height: 100%;
				.speed{
					margin-left: 15px;
					color: #fff;
					font-size :24px;
					height :100%;
					display: flex;
					> span
						{margin: auto;}
					}
				.full-screen{
					margin-left :15px;
					width: 40px;
					height :40px;
					background :url('../assets/images/full-screen-one.png') center/100% no-repeat;
					height: 100%;}
				.cancel{
					background: url('../assets/images/cancel-full-screen.png') center/100% no-repeat;
				}
			}
			}
	.control-wrap{
		width: 100%;
		height: 100%;
		position :absolute;
		top :0;
		left: 0;
		user-select :none;
		transform: translateZ(0);}
		// 调速面板
		.speed-tab{
			width :169px;
			height :100%;
			position :absolute;
			top :0;
			right: 0;
			background: rgba(0, 0, 0, 0.7);
			z-index: 1005;
			> ul{
				width: 100%;
				height: 100%;
				display: flex;
				flex-direction :column;
				justify-content: space-around;
				align-items: center;
				color: #fff;
				font-size: 24px;
				padding: 25px 0;
				> li{
					flex :1;
					width :100%;
					display: flex;
					> span{
						margin :auto;
						padding :5px 12px;
						&.select{
							border-radius: 5px;
							border: 2px solid #FFFFFF;
						}
					  }
					}
				}
			}
	.error-wrap{
		width: 100%;
		height :100%;
		position :absolute;
		top:0;
		left :0;
		user-select: none;
		transform :translateZ(0);
		display: flex;
		> .error-container{
			margin: auto;
			display: flex;
			flex-direction: column;
			justify-content :center;
			align-items: center;
			> .error-tip{
				font-size :30px;
				white-space: nowrap;
				font-weight: 500;
				color: #fff;}
			> .error-code{
				font-size :24px;
				white-space: nowrap;
				font-weight: 400;
				color: #999;
				margin-top: 20px;
				transform: scale(0.83);
				position :relative;}
				&.ls-pos{
					position :absolute;
					right :10px;
					bottom :20px;}
			> .error-btn{
				width :234px;
				height:74px;
				background: rgba(255, 255, 255, 0.8);
				border-radius :37px;
				border: 2px solid #FFFFFF;
				text-align: center;
				line-height :74px;
				color: #333;
				font-size:28px;
				white-space: nowrap;
				margin-top: 28px;
				font-weight: 500;
				position: relative;
				z-index :901;}
			}
		&.ps_bg{
			background :url(../assets/images/error_ps_bg.png) center/cover no-repeat;}
		&.ls_bg{
			background :url(../assets/images/error_ls_bg.png) center/cover no-repeat;}
		}
</style>
